package com.layer.common;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ClientThread extends Thread {

	private Socket socket;
	private MessageInterface msgProccessor;
	private ObjectInputStream dataInput;
	private ObjectOutputStream dataOutput;
	private boolean isConnected;

	public ClientThread(Socket client, MessageInterface node) {
		this.isConnected = true;
		this.socket = client;
		this.msgProccessor = node;
		
		try {
			this.dataOutput = new ObjectOutputStream(this.socket.getOutputStream());
			this.dataInput = new ObjectInputStream(this.socket.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Socket getSocket() {
		return socket;
	}

	@Override
	public void run() {
		while (this.isConnected){
			try {
				this.msgProccessor.receiveMessage((Message) this.dataInput.readObject());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void disconnect(){
		this.isConnected = false;
		this.send(new Message(Message.Type.DISCONNECT_CLIENT, this.socket.getLocalSocketAddress(), null, null));
		try {
			ClientThread.sleep(5000);
			this.dataInput.close();
			this.socket.close();
			this.dataOutput.flush();
			this.dataOutput.close();		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void send(Message msg) {
		try {
			this.dataOutput.writeObject(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
